<!-- GearMarket.vue - 二手渔具购物商城主页 -->
<template>
  <div class="gear-market">
    <!-- 页面头部横幅 -->
    <div class="market-header">
      <div class="header-content">
        <div class="header-text">
          <h1 class="market-title">
            <el-icon class="title-icon"><ShoppingCart /></el-icon>
            二手渔具商城
          </h1>
          <p class="market-subtitle">专业渔具，品质保证，让钓鱼更精彩</p>
        </div>
        <div class="header-stats">
          <div class="stat-item">
            <span class="stat-number">{{ products.length }}</span>
            <span class="stat-label">在售商品</span>
          </div>
          <div class="stat-item">
            <span class="stat-number">100%</span>
            <span class="stat-label">正品保证</span>
          </div>
          <div class="stat-item">
            <el-button 
              type="primary" 
              size="small" 
              @click="forceRefresh"
              :loading="loading"
            >
              <el-icon><RefreshRight /></el-icon>
              刷新商品
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选与搜索区域（美化样式） -->
    <div class="filter-container">
      <div class="filter-header">
        <h3 class="filter-title">
          <el-icon><Search /></el-icon>
          筛选商品
        </h3>
      </div>
      <div class="filter-row">
        <!-- 1. 商品分类筛选 -->
        <div class="filter-item category-filter">
          <label class="filter-label">商品分类</label>
          <el-select v-model="selectedCategory" placeholder="全部分类" size="small" @change="resetPagination">
            <el-option label="全部分类" value="all"></el-option>
            <el-option label="鱼竿系列" value="rod"></el-option>
            <el-option label="渔具配件" value="accessory"></el-option>
            <el-option label="钓鱼装备" value="equipment"></el-option>
            <el-option label="路亚专区" value="lure"></el-option>
          </el-select>
        </div>

        <!-- 2. 价格区间筛选 -->
        <div class="filter-item price-filter">
          <label class="filter-label">价格筛选</label>
          <el-select v-model="selectedPriceRange" placeholder="全部价格" size="small" @change="resetPagination">
            <el-option label="全部价格" value="all"></el-option>
            <el-option label="0-100元" value="0-100"></el-option>
            <el-option label="100-300元" value="100-300"></el-option>
            <el-option label="300-500元" value="300-500"></el-option>
            <el-option label="500元以上" value="500+"></el-option>
          </el-select>
        </div>

        <!-- 3. 排序方式 -->
        <div class="filter-item sort-filter">
          <label class="filter-label">排序方式</label>
          <el-select v-model="sortType" placeholder="默认排序" size="small" @change="resetPagination">
            <el-option label="默认排序" value="default"></el-option>
            <el-option label="价格从低到高" value="price-asc"></el-option>
            <el-option label="价格从高到低" value="price-desc"></el-option>
            <el-option label="最新发布" value="time-desc"></el-option>
          </el-select>
        </div>

        <!-- 4. 搜索框（优化样式） -->
        <div class="filter-item search-filter">
          <el-input placeholder="搜索渔具名称..." v-model="productSearch" class="search-input" clearable size="small">
            <template #append>
              <el-button icon="Search" size="small" @click="searchProducts">搜索</el-button>
            </template>
          </el-input>
        </div>
      </div>

    </div>


    <!-- 加载状态（优化骨架屏样式） -->
    <div v-if="loading" class="loading-container">
      <el-skeleton v-for="(item, index) in 6" :key="index" class="loading-card" :rows="3" animated />
    </div>

    <!-- 错误状态（优化提示样式） -->
    <div v-else-if="error" class="error-container">
      <el-alert :title="error" type="error" show-icon center class="error-alert" />
      <el-button type="primary" size="small" @click="fetchProducts" class="retry-btn">
        重新加载
      </el-button>
    </div>

    <!-- 无数据状态（区分“无搜索结果”和“无商品”） -->
    <div v-else-if="processedProducts.length === 0" class="empty-container">
      <el-empty :image="emptyImage" :description="emptyDescription" class="empty-content">
        <el-button type="primary" size="small" @click="resetFilters" class="reset-btn">
          重置筛选
        </el-button>
      </el-empty>
    </div>

    <!-- 商品列表（修改首页图片预览功能） -->
    <div v-else class="product-grid">
      <el-card class="product-card" shadow="hover" v-for="(product, index) in paginatedProducts"
        :key="product.productId || index">
        <!-- 商品图片（美化样式） -->
        <div class="product-img-container">
          <el-image :src="product.coverList[0] || productPlaceholder" :alt="product.productName" class="product-img"
            lazy fit="cover">
            <template #loading>
              <div class="image-loading">
                <el-icon class="loading-icon">
                  <Loading />
                </el-icon>
              </div>
            </template>
            <template #error>
              <div class="image-error">
                <el-icon class="error-icon">
                  <PictureFilled />
                </el-icon>
              </div>
            </template>
          </el-image>
          <!-- 新旧程度标签（美化样式） -->
          <div class="old-level-tag" :class="getLevelClass(product.oldLevel)">
            {{ getOldLevelText(product.oldLevel) }}
          </div>
          <!-- 自己的发布标签 -->
          <div v-if="isMyProduct(product)" class="my-product-tag">
            <el-icon><User /></el-icon>
            自己的发布
          </div>
          <!-- 悬停遮罩效果 -->
          <div class="image-overlay">
            <el-button type="primary" size="small" class="quick-view-btn" @click="viewProductDetail(product)">
              <el-icon><ChatDotRound /></el-icon>
              快速查看
            </el-button>
          </div>
        </div>

        <!-- 商品信息（美化布局） -->
        <div class="product-info">
          <h3 class="product-name" :title="product.productName">
            {{ product.productName }}
          </h3>
          <div class="product-price">
            <span class="price-symbol">¥</span>
            <span class="price-value">{{ product.price.toFixed(2) }}</span>
          </div>
          <div class="product-meta">
            <div class="meta-item">
              <el-icon class="meta-icon"><User /></el-icon>
              <span class="meta-text">卖家: {{ product.userDisplayName || `用户${product.userId}` }}</span>
            </div>
            <div class="meta-item">
              <el-icon class="meta-icon"><Clock /></el-icon>
              <span class="meta-text">{{ formatDate(product.creatTime) }}</span>
            </div>
          </div>
        </div>

        <!-- 商品操作（美化按钮） -->
        <div class="product-actions">
          <el-button type="primary" size="small" class="detail-btn" @click="viewProductDetail(product)">
            <el-icon><ChatDotRound /></el-icon>
            查看详情
          </el-button>
        </div>
      </el-card>
    </div>
    <!-- 购物车对话框：集成 Cart.vue 全部功能 -->
    <el-dialog
      v-model="cartDialogVisible"
      title="我的购物车"
      width="90%"
      :max-width="1200"
      :close-on-click-modal="false"
      :before-close="handleDialogClose"
      class="cart-dialog"
    >
      <div class="cart-dialog__content">
        <!-- 1. 购物车操作栏（全选+批量删除） -->
        <div class="cart-toolbar">
          <div class="select-all-section">
            <el-checkbox
              v-model="cartStore.isAllSelected"
              @change="cartStore.selectAll"
            >
              全选
            </el-checkbox>
            <span class="selected-count">
              已选 {{ cartStore.selectedCount }} 件商品
            </span>
          </div>
          <el-button
            type="danger"
            size="small"
            @click="cartStore.batchDeleteSelected"
            icon="Delete"
          >
            批量删除
          </el-button>
        </div>

        <!-- 2. 加载状态 -->
        <div v-if="cartStore.loading" class="loading-container">
          <el-skeleton :rows="3" animated class="loading-card" />
        </div>

        <!-- 3. 错误状态 -->
        <div v-else-if="cartStore.error" class="error-container">
          <el-alert
            :title="cartStore.error"
            type="error"
            show-icon
            center
          />
          <el-button
            type="primary"
            size="small"
            @click="cartStore.fetchCartList"
            class="retry-btn"
          >
            重新加载
          </el-button>
        </div>

        <!-- 4. 空购物车状态 -->
        <div v-else-if="cartStore.cartList.length === 0" class="empty-container">
          <el-empty
            image=""
            description="您的购物车还是空的~"
          >
            <el-button
              type="primary"
              size="small"
              @click="cartDialogVisible = false; $router.push('/gear/market')"
            >
              去逛逛渔具
            </el-button>
          </el-empty>
        </div>

        <!-- 5. 购物车商品列表（带滚动） -->
        <div v-else class="cart-list">
          <el-card
            class="cart-item-card"
            shadow="hover"
            v-for="item in cartStore.cartList"
            :key="item.cart_id"
          >
            <div class="cart-item">
              <!-- 选中复选框 -->
              <div class="item-select">
                <el-checkbox
                  v-model="item.is_selected"
                  @change="(val) => cartStore.toggleSelect(item.cart_id, val)"
                />
              </div>
              <!-- 商品图片 -->
              <div class="item-image">
                <el-image
                  :src="parseCoverList(item.coverList)[0] || productPlaceholder"
                  :alt="item.product_name"
                  fit="cover"
                  preview-teleported
                  :preview-src-list="[parseCoverList(item.coverList)[0] || productPlaceholder]"
                >
                  <template #loading>
                    <div class="image-loading">
                      <el-icon><Loading /></el-icon>
                    </div>
                  </template>
                  <template #error>
                    <div class="image-error">
                      <el-icon><PictureFilled /></el-icon>
                    </div>
                  </template>
                </el-image>
              </div>
              <!-- 商品信息 -->
              <div class="item-info">
                <h3 class="item-name" :title="item.product_name">
                  {{ item.product_name }}
                </h3>
                <div class="item-old-level">
                  <span class="level-label">新旧程度：</span>
                  <span
                    class="level-tag"
                    :class="getLevelClass(item.old_level)"
                  >
                    {{ getOldLevelText(item.old_level) }}
                  </span>
                </div>
                <div class="item-price">¥{{ item.price.toFixed(2) }}</div>
              </div>
              <!-- 数量显示（无加减功能） -->
              <div class="item-quantity">
                {{ item.quantity }}
              </div>
              <!-- 小计 -->
              <div class="item-subtotal">
                ¥{{ ((item.price ?? 0) * (item.quantity ?? 1)).toFixed(2) }}
              </div>
              <!-- 删除按钮 -->
              <div class="item-delete">
                <el-button
                  type="text"
                  color="danger"
                  size="small"
                  @click="cartStore.deleteCartItem(item.cart_id)"
                  icon="Delete"
                >
                  删除
                </el-button>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 6. 结算栏（固定在对话框底部） -->
        <div v-if="cartStore.cartList.length > 0" class="checkout-bar">
          <div class="checkout-summary">
            <span class="summary-text">
              已选 {{ cartStore.selectedCount }} 件商品，总价：
            </span>
            <span class="summary-total">
              ¥{{ cartStore.selectedTotalPrice }}
            </span>
          </div>
          <el-button
            type="primary"
            size="default"
            @click="handleCheckout"
            :disabled="cartStore.selectedCount === 0"
          >
            去结算
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 分页组件（新增，优化响应式） -->
    <div v-if="processedProducts.length > 0" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-sizes="[6, 12, 18]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="processedProducts.length" small />
    </div>

    <!-- 商品详情对话框（优化内容和样式） -->
    <el-dialog :title="selectedProduct?.productName || '商品详情'" v-model="detailVisible" width="80%" max-width="900px"
      :before-close="handleDialogClose1">
      <div v-if="selectedProduct" class="detail-content">
        <div class="detail-img-wrapper">
          <el-carousel height="400px" indicator-position="outside">
            <el-carousel-item v-for="(img, idx) in [1, 2, 3]" :key="idx">
              <!-- 详情页图片（保留预览功能，无需修改） -->
              <el-image :src="productPlaceholder" :alt="selectedProduct.productName" class="detail-img" fit="contain"
                :preview-src-list="[productPlaceholder]" preview-teleported />
            </el-carousel-item>
          </el-carousel>
        </div>

        <!-- 详情信息（新增卖家信息占位） -->
        <div class="detail-info-wrapper">
          <!-- 基本信息 -->
          <div class="basic-info">
            <div class="price-section">
              <span class="price-label">售价：</span>
              <span class="price-value">¥{{ selectedProduct.price.toFixed(2) }}</span>
            </div>
            <div class="level-section">
              <span class="level-label">新旧程度：</span>
              <el-rate v-model="selectedProduct.oldLevel" disabled show-score text-color="#ff9900"
                score-template="{value}星" class="level-rate" />
              <span class="level-text">{{ getOldLevelText(selectedProduct.oldLevel) }}</span>
            </div>
            <div class="time-section">
              <span class="time-label">发布时间：</span>
              <span class="time-value">{{ formatDate(selectedProduct.creatTime) }}</span>
            </div>
          </div>

          <!-- 商品描述（优化换行） -->
          <div class="desc-section">
            <h4 class="section-title">商品描述</h4>
            <div class="desc-content">
              {{ selectedProduct.productDetail }}
            </div>
          </div>

          <!-- 卖家信息（占位，后期可对接用户表） -->
          <div class="seller-section">
            <h4 class="section-title">卖家信息</h4>
            <div class="seller-info">
              <el-avatar class="seller-avatar" icon="User" size="medium"></el-avatar>
              <div class="seller-meta">
                <div class="seller-name">
                  卖家: {{ selectedProduct.userDisplayName || `用户${selectedProduct.userId}` }}
                </div>
                <div class="seller-rating">
                  <el-rate disabled :value="4.5" text-color="#ff9900" size="small"></el-rate>
                  <span class="rating-count">(128条评价)</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 对话框底部按钮（优化逻辑） -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailVisible = false">关闭</el-button>

          <el-button type="success" @click="handleAddCart">
            <el-icon>
              <ShoppingCart />
            </el-icon> 加入购物车
          </el-button>

          <el-button type="primary" @click="handleContactSeller">
            <el-icon>
              <ChatDotRound />
            </el-icon> 购买
          </el-button>


        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage, ElMessageBox, ElEmpty } from 'element-plus'
import { useRouter } from 'vue-router'
import { useCartStore } from '../../stores/cartStore'
import { productAPI, userAPI } from '@/api'
// 引入 Element Plus 图标
import {
  Search, Loading, PictureFilled, Clock,
  ChatDotRound, ShoppingCart, User, RefreshRight
} from '@element-plus/icons-vue'
import {
  ElDialog,
  ElCard,
  ElCheckbox,
  ElImage,
  ElSkeleton,
  ElAlert,
  ElButton,
  ElInput
} from 'element-plus'

export default {
  name: 'GearMarket',
  components: {
    Search, Loading, PictureFilled, Clock,
    ChatDotRound, ShoppingCart, User, RefreshRight,
    ElDialog,
    ElCard,
    ElCheckbox,
    ElImage,
    ElSkeleton,
    ElAlert,
    ElButton,
    ElInput,
    // 移除重复的 ElEmpty 声明
    ElEmpty
  },
  setup() {
    // -------------------------- 1. 基础响应式变量 --------------------------
    const productSearch = ref('') // 搜索关键词
    const detailVisible = ref(false) // 详情弹窗显示状态
    const selectedProduct = ref(null) // 当前选中的商品
    const products = ref([]) // 原始商品列表
    const loading = ref(false) // 加载状态
    const error = ref('') // 错误信息
    const router = useRouter() // 路由实例
    const cartStore = useCartStore() // 新增：创建Store实例
    const isCartButtonLoading = ref(false) // 控制按钮加载状态
     const currentProduct = ref({}) // 当前商品数据（从列表/详情中获取）
    const cartDialogVisible = ref(false)
    // 4. 商品搜索关键词（原有功能保留）
    const keyword = ref('')

    // -------------------------- 2. 筛选相关变量 --------------------------
    const selectedCategory = ref('all') // 选中的分类
    const selectedPriceRange = ref('all') // 选中的价格区间
    const sortType = ref('default') // 排序类型

    // -------------------------- 3. 分页相关变量 --------------------------
    const currentPage = ref(1) // 当前页码
    const pageSize = ref(10) // 每页条数

    // -------------------------- 4. 静态资源与文案 --------------------------
    // 统一商品占位图（渔具相关，可替换为自己的图片）
    const productPlaceholder = ref('')

    // 无数据时的图片和文案
    const emptyImage = ref('')
    const emptyDescription = ref('暂无相关渔具商品')
    // ---------------------- 核心逻辑：对话框控制 ----------------------
    // 监听对话框显示状态：弹出时加载购物车数据+检查登录
    watch(cartDialogVisible, (isVisible) => {
      if (isVisible) {
        const user = cartStore.checkLogin()
        // 未登录：关闭对话框+引导登录
        if (!user) {
          cartDialogVisible.value = false
          return
        }
        // 已登录：加载最新购物车数据
        cartStore.fetchCartList()
      }
    })
    // 对话框关闭前处理：重置错误状态
    const handleDialogClose = (done) => {
      cartStore.error = '' // 清空错误信息，避免下次打开残留
      done()
    }
        // ---------------------- 复用 Cart.vue 核心方法 ----------------------
    // 1. 处理商品新旧程度文本
    const getOldLevelText = (level) => {
      const levelMap = {
        1: '1成新',
        2: '2成新',
        3: '3成新',
        4: '4成新',
        5: '5成新',
        6: '6成新',
        7: '7成新',
        8: '8成新',
        9: '9成新',
        10: '全新'
      }
      return levelMap[level] || '未知'
    }
    // 3. 结算功能（与Cart.vue一致）
    const handleCheckout = () => {
      if (cartStore.selectedCount === 0) {
        return ElMessage.warning('请先选中要结算的商品')
      }
      ElMessageBox({
        title: '订单结算提示',
        message: `
          <div style="text-align: left;">
            <p>✅ 已选中 ${cartStore.selectedCount} 件商品</p>
            <p>💰 商品总价：¥${cartStore.selectedTotalPrice}</p>
            <p style="color: #909399;">ℹ️ 当前暂未开通支付功能，订单信息已记录</p>
          </div>
        `,
        type: 'info',
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确认',
        showCancelButton: false
      }).then(() => {
        ElMessage.success('订单已记录，可在「我的购买」中查看')
      })
    }

    // 检查用户是否登录
    const checkLoginStatus = () => {
      const token = localStorage.getItem('token')
      return !!token
    }

    // 获取当前用户ID
    const getCurrentUserId = () => {
      try {
        const userInfoStr = localStorage.getItem('userInfo')
        if (userInfoStr) {
          const info = JSON.parse(userInfoStr)
          if (info && (info.userId || info.user_id)) {
            return info.userId || info.user_id
          }
        }
      } catch {}
      
      // 从JWT token中获取用户ID作为备用
      try {
        const token = localStorage.getItem('token') || localStorage.getItem('authToken')
        if (token && token.includes('.')) {
          const payload = JSON.parse(atob(token.split('.')[1] || ''))
          if (payload && (payload.userId || payload.user_id || payload.uid || payload.id)) {
            return payload.userId || payload.user_id || payload.uid || payload.id
          }
        }
      } catch {}
      
      return null
    }

    // 判断是否为自己的商品
    const isMyProduct = (product) => {
      const currentUserId = getCurrentUserId()
      if (!currentUserId || !product) return false
      
      // 比较用户ID（支持多种字段格式）
      return product.userId === currentUserId || 
             product.user_id === currentUserId ||
             product.sellerId === currentUserId ||
             product.seller_id === currentUserId
    }

     // 核心：添加购物车点击事件（含登录判断）
    const handleAddToCart = async (product) => {
      const user = cartStore.checkLogin()
      
      // 1. 未登录：弹提示框，延迟1秒跳转登录
      if (!user) {
        ElMessageBox.confirm(
          '请先登录后再添加购物车',
          '未登录提示',
          {
            confirmButtonText: '前往登录',
            cancelButtonText: '取消',
            type: 'info',
            closeOnClickModal: false // 禁止点击空白关闭
          }
        ).then(() => {
          ElMessage.info('正在跳转到登录页...')
          // 延迟1秒跳转（带返回地址）
          setTimeout(() => {
            router.push({
              path: '/userLogin',
              query: { redirect: router.currentRoute.value.fullPath }
            })
          }, 1000)
        }).catch(() => {
          // 取消操作不处理
        })
        return
      }

      // 2. 已登录：调用添加购物车接口，弹购物车信息弹窗
      await cartStore.addCartItem(product, 1) // 调用已有的添加方法
      ElMessageBox({
        title: '添加成功',
        message: `
          <div style="text-align: left;">
            <p>已将【${product.product_name}】添加到购物车</p>
            <p>当前购物车共 ${cartStore.cartList.length} 件商品</p>
            <p>已选商品总价：¥${cartStore.selectedTotalPrice}</p>
          </div>
        `,
        type: 'success',
        dangerouslyUseHTMLString: true,
        confirmButtonText: '去购物车',
        cancelButtonText: '继续浏览'
      }).then(() => {
        router.push('/cart') // 去购物车页面
      }).catch(() => {
        // 继续浏览：关闭弹窗
      })
    }


    // 处理购物车按钮点击事件
    const handleCartButtonClick = () => {
      if (!checkLoginStatus()) {
        // 用户未登录，提示登录并跳转
        ElMessageBox.confirm(
          '您尚未登录，请先登录以查看购物车',
          '提示',
          {
            confirmButtonText: '前往登录',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          isCartButtonLoading.value = true // 显示加载状态
          setTimeout(() => {
            isCartButtonLoading.value = false
            router.push('/userLogin') // 跳转到登录页面
          }, 1000) // 模拟加载1秒
        }).catch(() => {
          ElMessage.info('已取消登录')
        })
      } else {
        // 用户已登录，跳转到购物车页面
        isCartButtonLoading.value = true // 显示加载状态
        setTimeout(() => {
          isCartButtonLoading.value = false
          router.push('/cart') // 跳转到购物车页面
        }, 500) // 模拟加载0.5秒
      }
    }

    /**
     * 处理新旧程度标签样式
     */
    const getLevelClass = (level) => {
      const classMap = {
        1: 'level-poor',
        2: 'level-old',
        3: 'level-normal',
        4: 'level-new',
        5: 'level-brandnew'
      }
      return classMap[level] || 'level-normal'
    }

    /**
     * 格式化日期
     */
    const formatDate = (dateString) => {
      if (!dateString) return '未知时间'
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    /**
     * 重置分页（筛选/搜索时调用）
     */
    const resetPagination = () => {
      currentPage.value = 1
    }

    /**
     * 重置所有筛选条件
     */
    const resetFilters = () => {
      productSearch.value = ''
      selectedCategory.value = 'all'
      selectedPriceRange.value = 'all'
      sortType.value = 'default'
      resetPagination()
      fetchProducts()
    }

    // -------------------------- 6. 数据请求与处理 --------------------------
    /**
     * 获取商品列表
     */
    // 用户信息缓存
    const userInfoCache = ref(new Map());

    // 获取用户信息（带缓存）
    const getUserInfo = async (userId) => {
      if (userInfoCache.value.has(userId)) {
        return userInfoCache.value.get(userId);
      }

      try {
        const response = await userAPI.getUserInfoById(userId);
        if (response.code === 0) {
          const userInfo = {
            userId: response.data.userId,
            username: response.data.username,
            nickName: response.data.nickName,
            displayName: response.data.displayName
          };
          userInfoCache.value.set(userId, userInfo);
          return userInfo;
        }
      } catch (error) {
      }
      
      // 返回默认值
      const defaultInfo = {
        userId: userId,
        username: `用户${userId}`,
        nickName: null,
        displayName: `用户${userId}`
      };
      userInfoCache.value.set(userId, defaultInfo);
      return defaultInfo;
    };

    // 强制刷新商品数据
    const forceRefresh = async () => {
      await fetchProducts()
    }

    const fetchProducts = async () => {
      try {
        loading.value = true;
        error.value = '';

        // 使用在售商品API，只显示可购买的商品
        const response = await productAPI.getAvailableProducts();

        if (response.code === 0 && Array.isArray(response.data)) {
          // 提取 product 对象中的数据
          products.value = response.data;
          
          // 为每个商品设置默认状态（如果状态为空）
          products.value.forEach((product, index) => {
            if (!product.status || product.status === '') {
              product.status = 'available'
            }
          });

          // 收集所有唯一的用户ID
          const userIds = [...new Set(products.value.map(product => product.userId).filter(Boolean))];
          
          // 批量获取用户信息
          const userInfoPromises = userIds.map(userId => getUserInfo(userId));
          const userInfos = await Promise.all(userInfoPromises);
          
          // 创建用户ID到显示名称的映射
          const userDisplayMap = new Map();
          userIds.forEach((userId, index) => {
            userDisplayMap.set(userId, userInfos[index].displayName);
          });
          
          // 为每个商品添加用户显示名称
          products.value.forEach(product => {
            if (product.userId) {
              product.userDisplayName = userDisplayMap.get(product.userId) || `用户${product.userId}`;
            }
          });

          emptyDescription.value = '暂无相关渔具商品';
        } else {
          products.value = [];
          emptyDescription.value = '暂无商品数据，敬请期待';
          ElMessage.warning('暂无有效的商品数据');
        }
      } catch (err) {
        
        // 处理401未授权错误
        if (err.response && err.response.status === 401) {
          // 不显示错误消息，因为request.js已经处理了token清除
          // 可以尝试其他公开接口或显示空状态
          products.value = [];
          emptyDescription.value = '商品列表加载中...';
        } else {
          error.value = '获取商品数据失败，请检查网络连接';
          products.value = [];
          ElMessageBox.alert(
            '无法连接到服务器，请稍后再试或联系管理员',
            '数据加载失败',
            { confirmButtonText: '确定', type: 'error' }
          );
        }
      } finally {
        loading.value = false;
      }
    };


    /**
     * 搜索商品（触发重新请求或筛选）
     */
    const searchProducts = () => {
      resetPagination()
      // 若后端支持搜索接口，可替换为：axios.get(`/api/product/search?keyword=${productSearch.value}`)
      // 这里先用前端筛选模拟
      if (productSearch.value) {
        emptyDescription.value = `未找到包含"${productSearch.value}"的商品`
      } else {
        emptyDescription.value = '暂无相关渔具商品'
      }
    }

    // -------------------------- 7. 筛选与排序逻辑（前端处理） --------------------------
    /**
     * 处理后的商品列表（筛选 + 排序）
     */
    const processedProducts = computed(() => {
      let result = [...products.value]

      // 1. 分类筛选
      if (selectedCategory.value !== 'all') {
        const categoryMap = {
          rod: ['手竿', '海竿', '路亚竿', '筏竿', '矶竿'], // 鱼竿关键词
          accessory: ['鱼线', '鱼钩', '浮漂', '太空豆', '抄网', '假饵'], // 配件关键词
          equipment: ['钓鱼箱', '钓椅', '渔具包', '鱼护', '打窝器', '保温杯', '钓鱼服'], // 装备关键词
          lure: ['路亚', '假饵', '水滴轮'] // 路亚专区关键词
        }
        const keywords = categoryMap[selectedCategory.value] || []
        result = result.filter(product =>
          keywords.some(keyword => product.productName.includes(keyword))
        )
      }

      // 2. 价格区间筛选
      if (selectedPriceRange.value !== 'all') {
        const [minPrice, maxPrice] = selectedPriceRange.value.split('-')
        result = result.filter(product => {
          const price = Number(product.price)
          if (maxPrice) {
            return price >= Number(minPrice) && price <= Number(maxPrice)
          } else {
            return price >= Number(minPrice.replace('+', ''))
          }
        })
      }

      // 3. 关键词搜索筛选
      if (productSearch.value) {
        const keyword = productSearch.value.trim().toLowerCase()
        result = result.filter(product =>
          product.productName.toLowerCase().includes(keyword) ||
          product.productDetail.toLowerCase().includes(keyword)
        )
      }

      // 4. 排序处理
      switch (sortType.value) {
        case 'price-asc': // 价格从低到高
          result.sort((a, b) => Number(a.price) - Number(b.price))
          break
        case 'price-desc': // 价格从高到低
          result.sort((a, b) => Number(b.price) - Number(a.price))
          break
        case 'time-desc': // 最新发布
          result.sort((a, b) => new Date(b.creatTime) - new Date(a.creatTime))
          break
        default:
          break
      }

      return result
    })

    /**
     * 安全解析 coverList 字段
     */
    const parseCoverList = (coverList) => {
      // 如果已经是数组，直接返回
      if (Array.isArray(coverList)) {
        return coverList;
      }
      
      // 如果是字符串，尝试解析
      if (typeof coverList === 'string') {
        // 如果是空字符串，返回空数组
        if (!coverList.trim()) {
          return [];
        }
        
        // 如果看起来像URL（以http开头），包装成数组
        if (coverList.startsWith('http')) {
          return [coverList];
        }
        
        // 尝试解析JSON字符串
        try {
          const parsed = JSON.parse(coverList);
          return Array.isArray(parsed) ? parsed : [parsed];
        } catch (error) {
          return [];
        }
      }
      
      // 其他情况返回空数组
      return [];
    };

    /**
     * 分页后的商品列表
     */
    const paginatedProducts = computed(() => {
      const startIndex = (currentPage.value - 1) * pageSize.value;
      const endIndex = startIndex + pageSize.value;

      // 解析 coverList 字段为数组
      return processedProducts.value
        .slice(startIndex, endIndex)
        .map(product => ({
          ...product,
          coverList: parseCoverList(product.coverList) // 使用安全解析函数
        }));
    });

    // -------------------------- 8. 分页事件处理 --------------------------
    const handleSizeChange = (val) => {
      pageSize.value = val
      resetPagination()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      // 滚动到列表顶部（优化体验）
      document.querySelector('.product-grid')?.scrollIntoView({ behavior: 'smooth' })
    }

    // -------------------------- 9. 商品交互事件 --------------------------
    /**
     * 查看商品详情
     */
    const viewProductDetail = (product) => {
      // 跳转到商品详情页
      router.push(`/gear/product/${product.productId}`)
    }

    /**
     * 关闭详情弹窗
     */
    const handleDialogClose1 = () => {
      detailVisible.value = false
      // 延迟清空选中商品（避免弹窗关闭时闪烁）
      setTimeout(() => {
        selectedProduct.value = null
      }, 300)
    }

    /**
     * 联系卖家
     */
    const handleContactSeller = () => {
      if (!selectedProduct.value) return
      ElMessage.success(`已打开与卖家${selectedProduct.value.userDisplayName || `用户${selectedProduct.value.userId}`}的购买窗口`)
      // 实际项目中实现购买功能
    }

    /**
     * 加入购物车
     */
    const handleAddCart = async () => {
      if (!selectedProduct.value) return
      // 调用Pinia的addCartItem，添加商品到购物车（默认数量1）
      await cartStore.addCartItem(selectedProduct.value, 1)
    }

    // -------------------------- 10. 页面初始化 --------------------------

    onMounted(async () => {
      await fetchProducts(); // 直接在钩子回调内执行异步请求
      
      // 监听订单创建事件，当有订单创建时刷新商品列表
      const handleOrderCreated = (event) => {
        // 根据文档，订单创建后商品状态变为reserved，需要立即刷新
        setTimeout(() => {
          fetchProducts()
        }, 200) // 增加延迟确保后端状态更新完成
      }
      
      // 监听订单取消事件，当有订单取消时刷新商品列表
      const handleOrderCancelled = (event) => {
        fetchProducts()
      }
      
      // 监听订单状态变化事件（支付成功、发货等）
      const handleOrderStatusChanged = (event) => {
        const { orderId, newStatus } = event.detail
        if (newStatus === 'paid') {
        }
        fetchProducts()
      }
      
      // 监听页面可见性变化，当页面重新可见时刷新商品列表
      const handleVisibilityChange = () => {
        if (!document.hidden) {
          fetchProducts()
        }
      }
      
      window.addEventListener('orderCreated', handleOrderCreated)
      window.addEventListener('orderCancelled', handleOrderCancelled)
      window.addEventListener('orderStatusChanged', handleOrderStatusChanged)
      document.addEventListener('visibilitychange', handleVisibilityChange)
      
      // 保存事件处理器引用，用于清理
      window._orderCreatedHandler = handleOrderCreated
      window._orderCancelledHandler = handleOrderCancelled
      window._orderStatusChangedHandler = handleOrderStatusChanged
      window._visibilityChangeHandler = handleVisibilityChange
    });

    onUnmounted(() => {
      // 清理事件监听器
      if (window._orderCreatedHandler) {
        window.removeEventListener('orderCreated', window._orderCreatedHandler)
        delete window._orderCreatedHandler
      }
      if (window._orderCancelledHandler) {
        window.removeEventListener('orderCancelled', window._orderCancelledHandler)
        delete window._orderCancelledHandler
      }
      if (window._orderStatusChangedHandler) {
        window.removeEventListener('orderStatusChanged', window._orderStatusChangedHandler)
        delete window._orderStatusChangedHandler
      }
      if (window._visibilityChangeHandler) {
        document.removeEventListener('visibilitychange', window._visibilityChangeHandler)
        delete window._visibilityChangeHandler
      }
    });
    // -------------------------- 11. 暴露给模板的变量/函数 --------------------------
    return {
      productSearch,
      detailVisible,
      selectedProduct,
      products,
      loading,
      error,
      selectedCategory,
      selectedPriceRange,
      sortType,
      currentPage,
      pageSize,
      productPlaceholder,
      emptyImage,
      emptyDescription,
      processedProducts,
      paginatedProducts,
      parseCoverList,
      getOldLevelText,
      getLevelClass,
      formatDate,
      resetPagination,
      resetFilters,
      fetchProducts,
      forceRefresh,
      getUserInfo,
      searchProducts,
      handleSizeChange,
      handleCurrentChange,
      viewProductDetail,
      handleDialogClose1,
      handleDialogClose,
      handleContactSeller,
      handleAddCart,
      handleAddToCart,
      cartStore,
      handleCartButtonClick,
      isCartButtonLoading,
      handleCartButtonClick,
      currentProduct,
      cartDialogVisible,
      cartStore,
      productPlaceholder,
      keyword,
      handleCheckout,
      getCurrentUserId,
      isMyProduct,
    }
  }
}
</script>

<style scoped lang="scss">
// 全局样式变量
$primary-color: #409eff; // 主色调（柔和蓝）
$success-color: #67c23a; // 成功色
$warning-color: #ff9900; // 警告色（新旧程度）
$danger-color: #f56c6c; // 危险色
$gray-light: #f5f7fa; // 浅灰色（背景）
$gray-mid: #e5e6eb; // 中灰色（边框）
$gray-dark: #606266; // 深灰色（文本）
$text-main: #303133; // 主要文本色
$text-secondary: #909399; // 次要文本色

// 页面容器
.gear-market {
  width: 100%;
  min-height: 100vh;
  padding: 0;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  box-sizing: border-box;
}

// 页面头部横幅
.market-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 60px 0;
  margin-bottom: 30px;
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="75" cy="75" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="50" cy="10" r="0.5" fill="rgba(255,255,255,0.05)"/><circle cx="10" cy="60" r="0.5" fill="rgba(255,255,255,0.05)"/><circle cx="90" cy="40" r="0.5" fill="rgba(255,255,255,0.05)"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
    opacity: 0.3;
  }

  .header-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: relative;
    z-index: 1;

    @media (max-width: 768px) {
      flex-direction: column;
      text-align: center;
      gap: 30px;
    }
  }

  .header-text {
    .market-title {
      font-size: 2.5rem;
      font-weight: 700;
      margin: 0 0 10px 0;
      display: flex;
      align-items: center;
      gap: 15px;

      .title-icon {
        font-size: 2.2rem;
        color: #ffd700;
      }

      @media (max-width: 768px) {
        font-size: 2rem;
        justify-content: center;
      }
    }

    .market-subtitle {
      font-size: 1.1rem;
      margin: 0;
      opacity: 0.9;
      font-weight: 300;
    }
  }

  .header-stats {
    display: flex;
    gap: 40px;

    @media (max-width: 768px) {
      gap: 30px;
    }

    .stat-item {
      text-align: center;

      .stat-number {
        display: block;
        font-size: 2rem;
        font-weight: 700;
        color: #ffd700;
        margin-bottom: 5px;
      }

      .stat-label {
        font-size: 0.9rem;
        opacity: 0.8;
      }
    }
  }
}

// 页面标题
.page-header {
  margin-bottom: 24px;
  text-align: center;

  .header-title {
    font-size: 24px;
    color: $text-main;
    margin-bottom: 8px;
    font-weight: 600;
  }

  .header-desc {
    font-size: 14px;
    color: $text-secondary;
  }
}

// 筛选容器
.filter-container {
  display: flex; // 使用 flex 布局
  align-items: center; // 垂直居中对齐
  justify-content: space-between; // 左右分布
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

  .filter-row {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 16px;

    .filter-item {
      display: flex;
      align-items: center;
      gap: 8px;

      .filter-label {
        font-size: 14px;
        color: $text-secondary;
        white-space: nowrap;
      }

      // 响应式：小屏幕下调整筛选项宽度
      @media (max-width: 768px) {
        flex: 1 1 calc(50% - 16px);

        &.search-filter {
          flex: 1 1 100%;
        }
      }

      @media (max-width: 480px) {
        flex: 1 1 100%;
      }
    }

    .search-input {
      width: 240px;

      @media (max-width: 768px) {
        width: 100%;
      }
    }
  }

  // 购物车按钮容器
  .cart-button-container {
    display: flex;
    align-items: center; // 垂直居中对齐

    .el-button {
      padding: 10px 20px;
      font-size: 14px;
      display: flex;
      align-items: center;
      gap: 8px;

      &:hover {
        background-color: #337ecc;
        border-color: #337ecc;
      }
    }
  }
}

// 加载状态容器
.loading-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  padding: 20px 0;

  .loading-card {
    width: calc(16.666% - 17px);
    height: 320px;
    border-radius: 8px;

    @media (max-width: 1200px) {
      width: calc(20% - 16px);
    }

    @media (max-width: 992px) {
      width: calc(25% - 15px);
    }

    @media (max-width: 768px) {
      width: calc(50% - 10px);
    }

    @media (max-width: 480px) {
      width: 100%;
    }
  }
}

// 错误状态容器
.error-container {
  text-align: center;
  padding: 40px 0;

  .error-alert {
    max-width: 500px;
    margin: 0 auto 16px;
  }

  .retry-btn {
    margin-top: 8px;
  }
}

// 无数据状态容器
.empty-container {
  text-align: center;
  padding: 60px 0;

  .empty-content {
    max-width: 400px;
    margin: 0 auto;
  }

  .reset-btn {
    margin-top: 16px;
  }
}

// 商品列表网格
.product-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
  padding: 10px 0;

  // 商品卡片（优化响应式布局）
  .product-card {
    width: calc(20% - 24px);
    border-radius: 8px;
    overflow: hidden;
    transition: all 0.3s ease;
    border: 1px solid $gray-mid;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 8px 16px rgba(64, 158, 255, 0.15);
      border-color: $primary-color;
    }

    // 响应式调整卡片宽度
    @media (max-width: 1200px) {
      width: calc(25% - 24px); // 每行显示 4 个商品
    }

    @media (max-width: 992px) {
      width: calc(33.333% - 24px); // 每行显示 3 个商品
    }

    @media (max-width: 768px) {
      width: calc(50% - 24px); // 每行显示 2 个商品
    }

    @media (max-width: 480px) {
      width: 100%; // 每行显示 1 个商品
    }
  }

  // 商品图片容器
  .product-img-container {
    position: relative;
    height: 200px;
    background-color: $gray-light;

    .product-img {
      width: 100%;
      height: 100%;
    }

    // 图片加载/错误状态
    .image-loading,
    .image-error {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      color: $text-secondary;

      .loading-icon,
      .error-icon {
        font-size: 24px;
      }
    }

    // 新旧程度标签
    .old-level-tag {
      position: absolute;
      top: 8px;
      left: 8px;
      padding: 2px 8px;
      border-radius: 12px;
      font-size: 12px;
      color: #fff;
      font-weight: 500;

      &.level-poor {
        background-color: $danger-color;
      }

      &.level-old {
        background-color: #ff6700;
      }

      &.level-normal {
        background-color: $warning-color;
      }

      &.level-new {
        background-color: #4e944f;
      }

      &.level-brandnew {
        background-color: $success-color;
      }
    }
  }

  // 商品信息
  .product-info {
    padding: 12px;

    .product-name {
      font-size: 14px;
      color: $text-main;
      margin-bottom: 8px;
      height: 40px;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      line-height: 1.4;
    }

    .product-price {
      font-size: 16px;
      color: $danger-color;
      font-weight: 600;
      margin-bottom: 6px;
    }

    .product-desc {
      font-size: 12px;
      color: $text-secondary;
      margin-bottom: 8px;
      height: 36px;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      line-height: 1.5;
    }

    .product-time {
      font-size: 12px;
      color: $text-secondary;
      display: flex;
      align-items: center;
      gap: 4px;

      .time-icon {
        font-size: 12px;
      }
    }
  }

  // 商品操作按钮
  .product-actions {
    display: flex;
    padding: 0 12px 12px;
    gap: 8px;

    .detail-btn {
      flex: 1;
      background-color: $primary-color;
      border-color: $primary-color;

      &:hover {
        background-color: #337ecc;
        border-color: #337ecc;
      }
    }

    .collect-btn {
      flex: 0 0 80px;
      color: $text-secondary;
      border-color: $gray-mid;

      &:hover {
        color: $warning-color;
        border-color: $warning-color;
        background-color: rgba(255, 153, 0, 0.05);
      }
    }
  }
}

// 分页容器
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  padding: 10px 0;
}

// 详情弹窗内容
.detail-content {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;

  // 详情图片区域
  .detail-img-wrapper {
    flex: 1 1 400px;

    .detail-img {
      width: 100%;
      height: 100%;
      object-fit: contain;
      background-color: $gray-light;
      border-radius: 4px;
    }
  }

  // 详情信息区域
  .detail-info-wrapper {
    flex: 1 1 400px;

    .section-title {
      font-size: 16px;
      color: $text-main;
      margin-bottom: 8px;
      padding-bottom: 4px;
      border-bottom: 1px solid $gray-mid;
    }

    // 基本信息
    .basic-info {
      margin-bottom: 20px;

      .price-section,
      .level-section,
      .time-section {
        margin-bottom: 12px;
        font-size: 14px;
        display: flex;
        align-items: center;
        gap: 8px;

        .price-label,
        .level-label,
        .time-label {
          color: $text-secondary;
          white-space: nowrap;
        }

        .price-value {
          font-size: 20px;
          color: $danger-color;
          font-weight: 600;
        }

        .level-rate {
          margin-right: 8px;
        }

        .level-text {
          color: $warning-color;
        }

        .time-value {
          color: $text-main;
        }
      }
    }

    // 商品描述
    .desc-section {
      margin-bottom: 20px;

      .desc-content {
        font-size: 14px;
        color: $text-main;
        line-height: 1.6;
        padding: 8px;
        background-color: $gray-light;
        border-radius: 4px;
        min-height: 100px;
      }
    }

    // 卖家信息
    .seller-section {
      .seller-info {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 10px;
        background-color: $gray-light;
        border-radius: 4px;

        .seller-avatar {
          background-color: $primary-color;
          color: #fff;
        }

        .seller-meta {
          .seller-name {
            font-size: 14px;
            color: $text-main;
            margin-bottom: 4px;
          }

          .seller-rating {
            font-size: 12px;
            color: $text-secondary;

            .rating-count {
              margin-left: 8px;
            }
          }
        }
      }
    }
  }
}

// 对话框底部按钮
.dialog-footer {
  display: flex;
  gap: 8px;
}
// 全局样式变量（与Cart.vue统一）
$primary-color: #409eff;
$success-color: #67c23a;
$warning-color: #ff9900;
$danger-color: #f56c6c;
$gray-light: #f5f7fa;
$gray-mid: #e5e6eb;
$text-main: #303133;
$text-secondary: #909399;

// GearMarket 原有样式保留...
.top-bar {
  display: flex;
  gap: 16px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
  .search-input {
    flex: 1;
    min-width: 200px;
  }
}

// ---------------------- 购物车对话框样式 ----------------------
.cart-dialog {
  .cart-dialog__content {
    padding: 10px 0;
  }

  // 1. 购物车操作栏
  .cart-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #fff;
    padding: 12px 20px;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    .select-all-section {
      display: flex;
      align-items: center;
      gap: 12px;
      .selected-count {
        font-size: 14px;
        color: $text-secondary;
      }
    }
  }

  // 2. 加载/错误/空状态
  .loading-container,
  .error-container,
  .empty-container {
    background: #fff;
    border-radius: 8px;
    padding: 40px;
    margin-bottom: 20px;
    text-align: center;
  }
  .loading-card {
    width: 100%;
  }
  .retry-btn {
    margin-top: 16px;
  }

  // 3. 商品列表（带滚动）
  .cart-list {
    display: flex;
    flex-direction: column;
    gap: 12px;
    margin-bottom: 20px;
    max-height: 500px; // 限制高度，避免溢出
    overflow-y: auto;
    padding-right: 10px;
    // 滚动条优化
    &::-webkit-scrollbar {
      width: 6px;
    }
    &::-webkit-scrollbar-thumb {
      background: $gray-mid;
      border-radius: 3px;
    }
  }

  // 4. 商品项卡片
  .cart-item-card {
    border: 1px solid $gray-mid;
    border-radius: 8px;
    overflow: hidden;
    .cart-item {
      display: flex;
      align-items: center;
      padding: 16px;
      gap: 20px;
      // 响应式布局
      @media (max-width: 768px) {
        flex-wrap: wrap;
        .item-select, .item-delete {
          flex: 1 1 100%;
          justify-content: center;
        }
        .item-image {
          flex: 1 1 120px;
        }
        .item-info {
          flex: 1 1 calc(100% - 140px);
        }
      }

      // 商品图片
      .item-image {
        flex: 0 0 80px;
        height: 80px;
        border-radius: 4px;
        overflow: hidden;
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
        .image-loading, .image-error {
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          color: $text-secondary;
          background: $gray-light;
        }
      }

      // 商品信息
      .item-info {
        flex: 1;
        min-width: 0; // 解决文本溢出
        .item-name {
          font-size: 14px;
          color: $text-main;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          margin-bottom: 8px;
        }
        .item-old-level {
          font-size: 12px;
          color: $text-secondary;
          margin-bottom: 8px;
          display: flex;
          align-items: center;
          gap: 8px;
          .level-tag {
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 12px;
            color: #fff;
            &.level-poor { background: $danger-color; }
            &.level-old { background: #ff6700; }
            &.level-normal { background: $warning-color; }
            &.level-new { background: #4e944f; }
            &.level-brandnew { background: $success-color; }
          }
        }
        .item-price {
          font-size: 14px;
          color: $danger-color;
          font-weight: 600;
        }
      }

      // 数量/小计/删除
      .item-quantity {
        flex: 0 0 120px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        color: $text-main;
      }
      .item-subtotal {
        flex: 0 0 100px;
        font-size: 14px;
        color: $text-main;
        font-weight: 500;
        text-align: center;
      }
      .item-delete {
        flex: 0 0 80px;
        display: flex;
        align-items: center;
        justify-content: center;
        button:hover {
          color: $danger-color;
          background: rgba(245, 108, 108, 0.05);
        }
      }
    }
  }

  // 5. 结算栏
  .checkout-bar {
    background: #fff;
    padding: 16px 20px;
    border-radius: 8px;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
    .summary-total {
      font-size: 18px;
      color: $danger-color;
      font-weight: 600;
    }
    button {
      padding: 8px 24px;
      &:disabled {
        background: $gray-mid;
        border-color: $gray-mid;
        cursor: not-allowed;
      }
    }
  }
}

// 新增美化样式
.market-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 60px 0;
  margin-bottom: 30px;
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="75" cy="75" r="1" fill="rgba(255,255,255,0.1)"/><circle cx="50" cy="10" r="0.5" fill="rgba(255,255,255,0.05)"/><circle cx="10" cy="60" r="0.5" fill="rgba(255,255,255,0.05)"/><circle cx="90" cy="40" r="0.5" fill="rgba(255,255,255,0.05)"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
    opacity: 0.3;
  }

  .header-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: relative;
    z-index: 1;

    @media (max-width: 768px) {
      flex-direction: column;
      text-align: center;
      gap: 30px;
    }
  }

  .header-text {
    .market-title {
      font-size: 2.5rem;
      font-weight: 700;
      margin: 0 0 10px 0;
      display: flex;
      align-items: center;
      gap: 15px;

      .title-icon {
        font-size: 2.2rem;
        color: #ffd700;
      }

      @media (max-width: 768px) {
        font-size: 2rem;
        justify-content: center;
      }
    }

    .market-subtitle {
      font-size: 1.1rem;
      margin: 0;
      opacity: 0.9;
      font-weight: 300;
    }
  }

  .header-stats {
    display: flex;
    gap: 40px;

    @media (max-width: 768px) {
      gap: 30px;
    }

    .stat-item {
      text-align: center;

      .stat-number {
        display: block;
        font-size: 2rem;
        font-weight: 700;
        color: #ffd700;
        margin-bottom: 5px;
      }

      .stat-label {
        font-size: 0.9rem;
        opacity: 0.8;
      }
    }
  }
}

// 美化筛选区域
.filter-header {
  padding: 20px 0 10px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);

  .filter-title {
    margin: 0;
    font-size: 1.2rem;
    font-weight: 600;
    color: $text-main;
    display: flex;
    align-items: center;
    gap: 8px;

    .el-icon {
      color: $primary-color;
    }
  }
}

// 美化商品卡片
.product-card {
  border-radius: 16px !important;
  overflow: hidden;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: 1px solid rgba(0, 0, 0, 0.05);
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);

  &:hover {
    transform: translateY(-8px) scale(1.02);
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
    border-color: $primary-color;
  }
}

// 美化商品图片容器
.product-img-container {
  position: relative;
  height: 200px;
  overflow: hidden;

  .image-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(45deg, rgba(64, 158, 255, 0.8), rgba(103, 194, 58, 0.8));
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: all 0.3s ease;

    .quick-view-btn {
      background: rgba(255, 255, 255, 0.9);
      color: $primary-color;
      border: none;
      border-radius: 25px;
      padding: 8px 16px;
      font-weight: 600;
      backdrop-filter: blur(10px);

      &:hover {
        background: white;
        transform: scale(1.05);
      }
    }
  }

  &:hover .image-overlay {
    opacity: 1;
  }
}

// 美化商品信息
.product-info {
  padding: 20px;

  .product-name {
    font-size: 1.1rem;
    font-weight: 600;
    color: $text-main;
    margin: 0 0 12px 0;
    line-height: 1.4;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  .product-price {
    display: flex;
    align-items: baseline;
    gap: 4px;
    margin-bottom: 15px;

    .price-symbol {
      font-size: 0.9rem;
      color: $danger-color;
      font-weight: 500;
    }

    .price-value {
      font-size: 1.3rem;
      font-weight: 700;
      color: $danger-color;
    }
  }

  .product-meta {
    display: flex;
    flex-direction: column;
    gap: 8px;

    .meta-item {
      display: flex;
      align-items: center;
      gap: 6px;
      font-size: 0.85rem;
      color: $text-secondary;

      .meta-icon {
        font-size: 0.9rem;
        color: $primary-color;
      }

      .meta-text {
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}

// 美化操作按钮
.product-actions {
  padding: 0 20px 20px;

  .detail-btn {
    width: 100%;
    border-radius: 25px;
    background: linear-gradient(45deg, $primary-color, #66b3ff);
    border: none;
    font-weight: 600;
    transition: all 0.3s ease;

    &:hover {
      background: linear-gradient(45deg, #337ecc, $primary-color);
      transform: translateY(-2px);
      box-shadow: 0 8px 20px rgba(64, 158, 255, 0.3);
    }
  }
}

// 美化新旧程度标签
.old-level-tag {
  position: absolute;
  top: 12px;
  left: 12px;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 0.75rem;
  font-weight: 600;
  color: white;
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);

  &.level-new {
    background: linear-gradient(45deg, #67c23a, #85ce61);
  }

  &.level-good {
    background: linear-gradient(45deg, #409eff, #66b3ff);
  }

  &.level-normal {
    background: linear-gradient(45deg, #e6a23c, #f0c78a);
  }

  &.level-old {
    background: linear-gradient(45deg, #f56c6c, #f89898);
  }
}

// 自己的发布标签样式
.my-product-tag {
  position: absolute;
  top: 12px;
  right: 12px;
  background: linear-gradient(135deg, #67c23a, #5cb85c);
  color: white;
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 12px;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  z-index: 2;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 4px;

  &:hover {
    transform: scale(1.05);
    box-shadow: 0 6px 16px rgba(103, 194, 58, 0.4);
  }

  .el-icon {
    font-size: 14px;
  }
}

</style>